import datetime

from lxml import etree

import GetYamlFile
from GetData import GetTestCase, GetSession

#获取对应项目人员bug数
from ReadExcel import Read_Excel


def get_map(title,names):
    zqj  =xk=whd= hml= ljt=wjh=hqh=zsg=zwp=czj=lbj=szs=zjm=ljl=0
    bug_name={
        "厉江涛":ljt,
        "王佳辉":wjh,
        "黄其涵":hqh,
        "吴浩东":whd,
        "周清江":zqj,
        "何牡禄":hml,
        "徐康":xk,
        "章卡":zsg,
        "张万平": zwp,
        "陈治建": czj,
        "李倍佳": lbj,
        "宋泽森": szs,
        "詹佳敏": zjm,
        "李剑龙": ljl,
    }
    for name in names:
        if name in bug_name.keys():
            bug_name[name]+=1

    list=[title,bug_name]
    return list
#获取模板需要的list数据 （在源有的基础上整合）
def get_bug_by_template_result():
    list1 = []
    YmlList = GetYamlFile.getYamlFile()
    Result = YmlList["Result"]
    BugPath = GetYamlFile.getBugPath("BugPath")
    readBook = Read_Excel(BugPath)
    allNum = readBook.get_RowNums(Result)
    print(allNum)
    for item in range(3,allNum):
        projectName=str(readBook.read_Excel(Result,item,1))
        bugTol=int(readBook.read_Excel(Result,item,2))
        NumberOfUnresolvedBugs=int(readBook.read_Excel(Result,item,3))
        numberOfNewBugs=int(readBook.read_Excel(Result,item,4))
        bugSolveToday=int(readBook.read_Excel(Result,item,5))
        bugClosedToday=int(readBook.read_Excel(Result,item,6))
        bug_result={
            "projectName":projectName,
            "bugTol":bugTol,
            "NumberOfUnresolvedBugs":NumberOfUnresolvedBugs,
            "numberOfNewBugs":numberOfNewBugs,
            "bugSolveToday":bugSolveToday,
            "bugClosedToday":bugClosedToday
        }
        print(bug_result)
        list1.append(bug_result)
    print(list1)
    return  list1
#获取总bug数及未解决bug数
def get_result(list1):
    list_result = []
    list_result2 = []
    session = GetSession.getSession()
    for item in list1:
        name=item[0]
        url=item[1]["url"]
        title=item[1]["title"]
        response1 = session.get("http://chandao.tpson.com.cn/zentao/my/")
        response=session.get(url)
        html = response.text
        # if "未解决BUG数" == title:
        #     print(html)
        html = etree.HTML(html)
        if "BUG总数" ==title:
            allBug=html.xpath("//*[@id='mainMenu']/div[2]/a[1]/span[2]/text()")
        else:
            allBug=html.xpath("//*[@id='mainMenu']/div[2]/a[7]/span[2]/text()")
        # allBug=html.xpath("//*[@id='bugForm']/div[3]/ul/li[1]/div/strong[1]/text()")
        # print(allBug)
        if allBug :
            num = int(allBug[0])
            result={
                "name":name,
                "type":title,
                "bug":num
            }
            list_result.append(result)

            if "未解决BUG数" == title and num<=20:
                names = html.xpath("//*/td[8]/a/span/text()")
                list2=get_map(name,names)
                list_result2.append(list2)
            elif "未解决BUG数" == title and num>=20:
                url=item[1]["url"][:-5]+"-0"+"--"+str(num)+"-2000-1.html"
                response1 = session.get("http://chandao.tpson.com.cn/zentao/my/")
                response = session.get(url)
                html = response.text
                # print(html)
                html = etree.HTML(html)
                names = html.xpath("//*/td[8]/a/span/text()")
                list2 = get_map(name, names)
                list_result2.append(list2)
            else:
                pass
        else:
            result = {
                "name": name,
                "type": title,
                "bug": 0
            }
            list_result.append(result)
    print("总数"+str(list_result))
    print("研发对应未解决bug数"+str(list_result2))
    return list_result,list_result2
def save_info(infos):
    pass

def getANDsave(url):
    pass

#获取搜索结果
def get_search_result(list1,headers):
    list_result=[]
    session = GetSession.getSession()
    for item in list1:
        name=item[0]
        num=item[1]["number"]
        type =item[1]["type"]
        url=item[1]["url"]
        title=item[1]["title"]
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        data={
            "fieldconfirmed":"ZERO",
            "fieldproduct":num,
            "fieldmodule":"0",
            "fieldpri":"0",
            "andOr1":"AND",
            "field1":type,
            "operator1":"=",
            "value1":today,
            "module":"bug",
            "groupItems":"3",
            "formType":"lite"
        }
        response1 = session.get("http://chandao.tpson.com.cn/zentao/my/")
        content=session.post("http://chandao.tpson.com.cn/zentao/search-buildQuery.html",data,headers=headers)
        response = session.get(url)
        html = response.text
        print(html)
        html = etree.HTML(html)
        allBug = html.xpath("//*[@id='bugForm']/div[3]/div[3]/strong[1]/text()")
        if allBug:
            result={
                "name":name,
                "type":title,
                "bug":allBug[0]
            }
        else:
            result={
                "name":name,
                "type":title,
                "bug":0
            }
        list_result.append(result)
    print(list_result)
    return list_result

#获取所有项目过期bug数
def get_unresolved_bugs_result(list1):
    list_result = []
    session = GetSession.getSession()
    for item in list1:
        # print(item)
        name=item[0]
        url=item[1]["url"]
        title=item[1]["title"]
        response1 = session.get("http://chandao.tpson.com.cn/zentao/my/")
        response = session.get(url)
        html = response.text
        html = etree.HTML(html)
        bugIds = html.xpath("//*/td[1]/a/text()")
        # print(bugIds)
        bugDescribes = html.xpath("//*/td[4]/a/text()")
        # print(bugDescribes)
        bugByPs = html.xpath("//*/td[8]/a/span/text()")
        delaytimes = html.xpath("//*/td[9]/text()")
        # print(bugByPs)
        if len(bugByPs)!=0:
            for i in range(0,len(bugByPs)):
                result={
                    "name":name,
                    "bugId" : bugIds[i],
                    "bugDescribe" :bugDescribes[i],
                    "bugByP" :bugByPs[i],
                    "delaytime":delaytimes[i]
                }
                list_result.append(result)
    print("过期bug：",list_result)
    return  list_result
def pltcase():
    pass


if __name__ == '__main__':
    headers={
        "Content-Type":"application/x-www-form-urlencoded",
    }
    # list1=GetTestCase.get_serch_test_case()
    list1 = [('数字用电', {'title': '今日已解决', 'number': 61.0, 'type': 'resolvedDate',
                       'url': 'http://chandao.tpson.com.cn/zentao/bug-browse-61-0-bySearch-myQueryID.html'})]

    # result1 = get_search_result(list1,headers)
    # list2=GetTestCase.get_unresolved_bugs_case()
    # result2=get_unresolved_bugs_result(list2)
    # print(result2)
    # get_bug_by_template_result()
    # localtime1 = time.strptime(strtime1, '%m%d')
    list4 =GetTestCase.get_test_case()
    result3=get_result(list4)


